package com.iamteer.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamteer.factory.BeanFactory;
import com.iamteer.service.ICategoryService;
import com.iamteer.service.IDinnerTableService;
import com.iamteer.service.IDishService;
import com.iamteer.utils.WebUtils;
/**
 * 项目中通用的 Servlet，所有的 Servlet 都继承此类
 * @author Chuck
 *
 */
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// 创建 Service
	protected ICategoryService categoryService = BeanFactory.getInstance(
			"categoryService", ICategoryService.class);
	protected IDinnerTableService dinnerTableService = BeanFactory.getInstance(
			"dinnerTableService", IDinnerTableService.class);
	protected IDishService dishService = BeanFactory.getInstance(
			"dishService", IDishService.class);
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 保存跳转资源（方法的返回值）
		Object uri = null;
		// 获取操作类型[约定：操作类型的值必须对应Servlet 中的方法名称]
		String methodName = request.getParameter("method");
		
		try {
			// 1. 获取当前运行类的字节码
			Class clazz = this.getClass();
			// 2. 获取当前执行的方法的 Method 类型
			Method method = clazz.getDeclaredMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			// 3. 执行方法
			uri = method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			uri = "/error/error.jsp";
		}
		WebUtils.goTo(request, response, uri);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
